// 缓存服务
class CacheService {
  constructor() {
    this.cache = new Map();
    this.cacheTimeout = 5 * 60 * 1000; // 5分钟缓存过期时间
  }

  /**
   * 生成缓存键
   * @param {string} cityName - 城市名称
   * @returns {string} 缓存键
   */
  generateCacheKey(cityName) {
    return `weather_${cityName.toLowerCase().trim()}`;
  }

  /**
   * 设置缓存
   * @param {string} cityName - 城市名称
   * @param {Object} data - 要缓存的数据
   */
  set(cityName, data) {
    const key = this.generateCacheKey(cityName);
    const cacheItem = {
      data,
      timestamp: Date.now(),
      expiresAt: Date.now() + this.cacheTimeout
    };
    
    this.cache.set(key, cacheItem);
    
    // 清理过期缓存
    this.cleanExpiredCache();
  }

  /**
   * 获取缓存
   * @param {string} cityName - 城市名称
   * @returns {Object|null} 缓存的数据，如果不存在或已过期则返回null
   */
  get(cityName) {
    const key = this.generateCacheKey(cityName);
    const cacheItem = this.cache.get(key);
    
    if (!cacheItem) {
      return null;
    }
    
    // 检查是否过期
    if (Date.now() > cacheItem.expiresAt) {
      this.cache.delete(key);
      return null;
    }
    
    return cacheItem.data;
  }

  /**
   * 检查缓存是否存在且有效
   * @param {string} cityName - 城市名称
   * @returns {boolean} 是否存在有效缓存
   */
  has(cityName) {
    return this.get(cityName) !== null;
  }

  /**
   * 删除指定城市的缓存
   * @param {string} cityName - 城市名称
   */
  delete(cityName) {
    const key = this.generateCacheKey(cityName);
    this.cache.delete(key);
  }

  /**
   * 清空所有缓存
   */
  clear() {
    this.cache.clear();
  }

  /**
   * 清理过期的缓存项
   */
  cleanExpiredCache() {
    const now = Date.now();
    
    for (const [key, cacheItem] of this.cache.entries()) {
      if (now > cacheItem.expiresAt) {
        this.cache.delete(key);
      }
    }
  }

  /**
   * 获取缓存统计信息
   * @returns {Object} 缓存统计
   */
  getStats() {
    const now = Date.now();
    let validCount = 0;
    let expiredCount = 0;
    
    for (const cacheItem of this.cache.values()) {
      if (now > cacheItem.expiresAt) {
        expiredCount++;
      } else {
        validCount++;
      }
    }
    
    return {
      total: this.cache.size,
      valid: validCount,
      expired: expiredCount,
      cacheTimeout: this.cacheTimeout
    };
  }

  /**
   * 设置缓存过期时间
   * @param {number} timeout - 过期时间（毫秒）
   */
  setCacheTimeout(timeout) {
    this.cacheTimeout = timeout;
  }

  /**
   * 获取所有缓存的城市列表
   * @returns {Array<string>} 城市名称列表
   */
  getCachedCities() {
    const cities = [];
    const now = Date.now();
    
    for (const [key, cacheItem] of this.cache.entries()) {
      if (now <= cacheItem.expiresAt) {
        // 从缓存键中提取城市名称
        const cityName = key.replace('weather_', '');
        cities.push(cityName);
      }
    }
    
    return cities;
  }
}

// 创建单例实例
const cacheService = new CacheService();

export default cacheService;